package org.zhao.nettydemos.protocol;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.zhao.nettydemos.echoServer.NettyEchoClientHandler;
import org.zhao.nettydemos.entity.JsonMsg;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @Auther: xiaohui.zhao
 * @Date: 2021/9/16 17:49
 * @Description:
 */
@Slf4j
public class JsonSendClient {

    static String content = "张三李四王麻子admin123!@#$%^&";

    Bootstrap bootstrap = new Bootstrap();


    public void runClient(){
        EventLoopGroup workerLoopGroup = new NioEventLoopGroup();

        try{
            // 1. 设置反应器轮询组
            bootstrap.group(workerLoopGroup);
            // 2. 设置nio类型的通道
            bootstrap.channel(NioSocketChannel.class);
            // 3. 设置ip + port
            bootstrap.remoteAddress("127.0.0.1",18899);
            // 4. 设置通道参数
            bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            // 5.  装配子通道流水线
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    // 管理子通道中的handler
                    // 向子通道流水线添加一个handler
                    socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
                    socketChannel.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));

                }
            });

            ChannelFuture channelFuture = bootstrap.connect();
            channelFuture.addListener((ChannelFuture fetureListener) -> {
                if(fetureListener.isSuccess()){
                    log.info("EchoClient 客户端连接成功");
                } else{
                    log.info("EchoClient 客户端连接失败");
                }
            });
            channelFuture.sync();  // 阻塞到连接成功

            Channel channel = channelFuture.channel();

            for(int i = 0;i<100;i++){
                JsonMsg user = new JsonMsg();
                user.setId(i);
                user.setContent(content);

                channel.writeAndFlush(user.convertToJson());
            }

            channel.flush();

            ChannelFuture closeFuture = channel.closeFuture();
            closeFuture.sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            workerLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new JsonSendClient().runClient();
    }

}